import { Card, Form, Input, Modal, Spin } from 'antd';
import React, { useCallback, useContext, useState } from 'react';
import PubSub from 'pubsub-js';
import FlowContext from '@/pages/Flow/FlowContext';
import request from '@/utils/request';
import VersionPageTable from '../../VersionPageTable';
import Main from '@/pages/HttpDataSource/Main';

function HttpDataSourcePanel({ form, node, update }) {
  const { getFieldDecorator, validateFields } = form;
  const { label, nodeCode, nodeId, nodeVersionId } = node;

  const { state } = useContext(FlowContext);
  const { processId, readOnly: pageReadOnly, versionId: processVersionId } = state;
  const [loading, setLoading] = useState(false);
  const isEdit = !!nodeId;

  const [readOnly, setReadOnly] = useState(isEdit);
  const [visible, setVisible] = useState(false);
  const [config, setConfig] = useState({});

  const showModal = useCallback(data => {
    setConfig(data);
    setVisible(true);
  }, []);

  const onSave = useCallback(() => {
    validateFields((err, values) => {
      if (!err) {
        setLoading(true);
        if (isEdit) {
          request
            .post(`/httpDataSource/updateHttpDataSource`, {
              data: { ...values, dataSourceId: nodeId },
            })
            .then(() => {
              update({
                label: values.dataSourceName,
                nodeCode: values.dataSourceCode,
              });
              setReadOnly(true);
              PubSub.publish(`nodeSave_${processId}_${processVersionId}`);
            })
            .finally(() => {
              setLoading(false);
            });
        } else {
          request
            .post(`/httpDataSource/createHttpDataSource?processVersionId=${processVersionId}`, {
              data: { ...values, processId },
            })
            .then(({ dataSourceId }) => {
              update({
                nodeId: dataSourceId,
                label: values.dataSourceName,
                nodeCode: values.dataSourceCode,
              });
              setReadOnly(true);
              PubSub.publish(`nodeSave_${processId}_${processVersionId}`);
            })
            .finally(() => {
              setLoading(false);
            });
        }
      }
    });
  }, [isEdit, nodeId, processId, processVersionId, update, validateFields]);

  const renderExtra = useCallback(() => {
    if (pageReadOnly) {
      return null;
    }
    return readOnly ? <a onClick={() => setReadOnly(false)}>编辑</a> : <a onClick={onSave}>保存</a>;
  }, [onSave, pageReadOnly, readOnly]);

  return (
    <Card type="inner" size="small" title="HTTP数据源" bordered={false} extra={renderExtra()}>
      <Spin spinning={loading}>
        <Form>
          <Form.Item label="数据源名称">
            {getFieldDecorator('dataSourceName', {
              initialValue: label,
              rules: [
                {
                  required: true,
                  message: '数据源名称不能为空',
                },
              ],
            })(<Input disabled={readOnly} placeholder="请输入" />)}
          </Form.Item>
          <Form.Item label="数据源编码">
            {getFieldDecorator('dataSourceCode', {
              initialValue: nodeCode,
              rules: [
                {
                  required: true,
                  message: '数据源编码不能为空',
                },
              ],
            })(<Input disabled={readOnly} placeholder="请输入" />)}
          </Form.Item>
        </Form>
        {isEdit ? (
          <VersionPageTable
            style={{ marginTop: '16px' }}
            element="httpDataSource"
            elementIdKey="dataSourceId"
            elementId={nodeId}
            elementVersionId={nodeVersionId}
            onClickConfig={({ elementId, versionId, readOnly }) => {
              showModal({ dataSourceId: elementId, versionId, readOnly });
            }}
            readOnly={state.readOnly}
            onValidVersion={nodeVersionId => {
              update({ nodeVersionId });
              PubSub.publish(`nodeSave_${processId}_${processVersionId}`);
            }}
          />
        ) : null}
        <Modal
          width={700}
          title="HTTP数据源配置"
          visible={visible}
          onCancel={() => setVisible(false)}
          destroyOnClose
          footer={null}
        >
          <Main {...config} onCancel={() => setVisible(false)} />
        </Modal>
      </Spin>
    </Card>
  );
}

export default Form.create()(HttpDataSourcePanel);
